<?php


namespace app\reception\controller;


use app\backstage\model\Backhaul;
use app\backstage\model\KlOrder;
use app\backstage\model\ManagerUser;
use app\backstage\model\Order;
use app\common\model\ChangeLog;
use app\common\model\RechargeActivity;
use app\common\model\RechargeItem;
use app\reception\classs\AdvertBehavior;
use app\reception\logic\LogLogic;
use app\reception\logic\PayLogic;
use think\Db;

class Pay extends Common
{
    protected $middleware = [
        'VerifyAuth' => ['except' => []],
    ];


    public function placeOrder()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\reception\validate\PayValidate.placeOrder');
        if (true !== $result) {
            return errJson($result);
        }
        $payId = input('pay_item_id');
        $payType = input('pay_type');
        $nid = input('nid', 0);
        $item = RechargeItem::get($payId);
        if (!$item) {
            return errJson('充值项不存在');
        }
        if ($nid) {
            $novel = \app\common\model\Novel::get($nid);
            if (!$novel) {
                return errJson('小说不存在');
            }
        }
        $activityId = 0;
        if ($item['is_activity'] == 1) {
            $activity = RechargeActivity::where("item_id", $item->id)->find();
            if (!$activity) {
                return errJson('活动不存在');
            } else {
                $activityId = $activity->id;
                if ($activity->pay_times == 1) {
                    $count = Db::table("pay_order_success")->where(['uid' => $this->uid, 'recharge_activity_id' => $activityId])->count();
                    if ($count >= 1) {
                        return errJson('您已充值过该活动，下单失败');
                    }
                }
            }
        }
        /**获取支付号*/
        $payLogic = new PayLogic();
        $paymentNumber = $payLogic->getPaymentNumber($this->quickAppId, $payType);
        if (!$paymentNumber) {
            return errJson('未设置支付号');
        }
        if ($this->user->userId == '36cecec57756f3d27') {
            return errJson('开发用户不允许起吊');
        }
        $changeWhere[] = ['uid', '=', $this->uid];
        $changeWhere[] = ['channel_id', '=', $this->user->channel_id];
        $changeWhere[] = ['link_id', '=', $this->user->link_id];
        $change_date = ChangeLog::where($changeWhere)->force('uid')->order("change_date desc")->value('change_date');
        $date = date("Y-m-d");
        $advertMediaId = 0;
        if ($this->user->link_id){
            $advertMediaId = Backhaul::where("link_id", $this->user->link_id)->value('advert_media_id') ?? 0;
        }

        $orderData = [
            'uid' => $this->uid,
            'channel_id' => $this->user->channel_id,
            'quick_id' => $this->user->quick_id,
            'agent_id' => $this->user->agent_id,
            'ip_addr' => request()->ip(),
            'recharge_type' => $activityId > 0 ? 2 : 1,
            'recharge_activity_id' => $activityId,
            'user_reg_date' => $this->user->regdate,
            'out_trade_no' => $payLogic->generateOrderNumber(),
            'trade_no' => '',
            'total_fee' => $item['total_fee'],
            'order_desc' => $item['desc'],
            'status' => 1,
            'chargefrom' => $paymentNumber->id,
            'pay_time' => 0,
            'type' => $item['vipdays'] > 0 ? 2 : 1,
            'virtual_currency' => $item['virtual_currency'],
            'point_gift' => $item['point_gift'],
            'vipdays' => $item['vipdays'],
            'pay_type' => $payType,
            'recharge_times' => $this->user->pay_times,
            'nid' => $nid,
            'link_id' => $this->user->link_id,
            'phone_model' => $this->user->provider,
            'advert_media_id' => $advertMediaId,
            'is_report' => 1,
            'user_source_date' => $change_date ? $change_date : $this->user->regdate,
            'create_date' => $date,
            'ip_blocked' => $this->user->ip_blocked
        ];
        $klSwitch = $this->klJudge($orderData['channel_id'], $orderData['agent_id']);
        if ($klSwitch == 1 && $item['total_fee'] > 1000) {//为了安全10块钱以下的不扣
            //扣量订单
            $order = new KlOrder();
            $oid = $order->insertGetId($orderData);
            if ($oid) {
                try {
                    return $payLogic->callPayment($orderData, $paymentNumber);
                }catch (\Exception $e){
                    LogLogic::addLog('kl_callPayment', $e->getMessage(), $this->uid, $this->quickAppId);
                    return errJson($e->getMessage());
                }
            } else {
                return errJson('创建订单异常失败');
            }
        }else{
            //正常订单
            $order = new Order();
            $oid = $order->insertGetId($orderData);
            if ($oid) {
                //记录订单广告相关数据
                $AdvertBehavior = new AdvertBehavior();
                $AdvertBehavior->writeOrderRecord($orderData,$oid);
                try {
                    return $payLogic->callPayment($orderData, $paymentNumber);
                }catch (\Exception $e){
                    LogLogic::addLog('callPayment', $e->getMessage(), $this->uid, $this->quickAppId);
                    return errJson($e->getMessage());
                }
            } else {
                return errJson('创建订单异常失败');
            }
        }
    }

    /**
     * 扣量判断
     * @param $channelId
     * @param $agentId
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function klJudge($channelId, $agentId)
    {
        if ($channelId) {
            $klSwitch = 1;
            $kl = Db::table("pay_order_kl_config")->where("channel_id", $channelId)->find();
            if (!$kl || $kl['switch'] != 1) {
                $klSwitch = 0;
            }
            //用户群体
            if ($klSwitch && $kl['user_group'] == 1) {
                if (!$this->user->pay_times) {
                    $klSwitch = 0;
                }
            }
            //满注册天数
            if ($klSwitch && $kl['register_judg'] == 1) {
                $dateDifference = intval((time() - strtotime($this->user->regdate)) / (60 * 60 * 24));
                if ($dateDifference <= $kl['register_day']) {
                    $klSwitch = 0;
                }
            }
            //登录判断
            if ($klSwitch && $kl['login_judg'] == 1) {
                $last_login_time = ManagerUser::where("id", $channelId)->value('last_login_time');
                $time = time();
                $jgTime = 3600 * $kl['login_hour'];
                if (($time - strtotime($last_login_time)) < $jgTime) {
                    $klSwitch = 0;
                }
                $last_login_time = ManagerUser::where("id", $agentId)->value('last_login_time');
                if (($time - strtotime($last_login_time)) < $jgTime) {
                    $klSwitch = 0;
                }
            }
            //前500个用户判断
            if ($klSwitch){
                $fastUIds = Db::table("quick_user_" . $this->quickAppId)->where("source_channel_id", $this->user->source_channel_id)->cache(3600)->order("id asc")->page(1, 500)->column('id');
                if (in_array($this->uid, $fastUIds) && $this->uid) {
                    $klSwitch = 0;
                }
            }
            if ($klSwitch) {
                $random_num = mt_rand(1, 100);
                if ($random_num > (100 * $kl['odds'])) {
                    $klSwitch = 0;
                }
            }
        } else {
            $klSwitch = 0;
        }
        return $klSwitch;
    }


    /**
     * 获取唤起微信收银台的referer域名
     * @return \think\response\Json
     */
    public function getReferer()
    {
        $payLogic = new PayLogic();
        $paymentNumber = $payLogic->getPaymentNumber($this->quickAppId, 1);
        if (!$paymentNumber) {
            return errJson('未设置支付号');
        }
        $data['referer'] = $paymentNumber['referer'];
        return sucJson($data);
    }
}